/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.ruoyi.cost.controller;

import com.ruoyi.cost.domain.Post;
import com.ruoyi.cost.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/account/post")
public class PostController {

	@Autowired
	private UnitService unitService;

	@GetMapping("treeData")
	public ResponseEntity<List <Post> > treeData() {
		List<Post> list = unitService.list1();
		List<Post> posts = buildMenuTree(list);

		return ResponseEntity.ok ( posts );
	}

	public static List<Post> buildMenuTree(List<Post> flatMenuList) {
		// 创建一个Map用于根据id快速查找节点
		Map<String, Post> menuMap = new HashMap<>();
		for (Post menuItem : flatMenuList) {
			menuMap.put(menuItem.getId(), menuItem);
		}

		List<Post> menuTree = new ArrayList<>();
		for (Post menuItem : flatMenuList) {
			if (menuItem.getParentId() == null) { // 根节点
				menuTree.add(menuItem);
			} else {
				Post parent = menuMap.get(menuItem.getParentId());
				if (parent != null) {
					parent.getChildren().add(menuItem);
				}
			}
		}

		return menuTree;
	}

}
